package com.sunrate.investingquote.service.router.comparator.test.compare.v1;

import com.sunrate.investingquote.bean.router.ChannelPriorityConfig;
import com.sunrate.investingquote.bean.router.ChannelRouter;
import com.sunrate.investingquote.dto.router.comparator.RouterSortContext;

import java.util.Comparator;

/**
 * @author yyh
 * @description:
 * @date 2023/07/04/ 11:49
 */
public abstract class ComparatorCreator {

    int order;

    ComparatorCreator next;


    void createAndInvokeNext(ChainParam chainParam) {
        if (support(chainParam)) {
            chainParam.setComparator(chainParam.getComparator().thenComparing(create(chainParam)));
        }
        if (next != null) {
            next.createAndInvokeNext(chainParam);
        }
    }

    protected abstract Comparator<RouterSortContext<ChannelRouter>> create(ChainParam chainParam);

    public void setNext(ComparatorCreator next) {
        this.next = next;
    }

    protected void setOrder(ChainParam chainParam) {
        this.order = chainParam.getConfigs().stream().filter(o -> getCode().equals(o.getCode())).map(ChannelPriorityConfig::getSortNum).findAny().orElse(Integer.MIN_VALUE);
    }

    int getOrder() {
        return this.order;
    }


    protected abstract String getCode();


    protected boolean support(ChainParam chainParam) {
        return chainParam.getConfigs().stream().anyMatch(o -> getCode().equals(o.getCode()));
    }
}
